package com.fms.kccc.fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.fms.kccc.R;
import com.fms.kccc.adapter.ImageListViewAdapter;
import com.fms.kccc.object.ImageContent;
import com.fms.kccc.util.Common;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class NewFragmentTab extends SherlockFragment {
	private PullToRefreshListView lvNewFragment;
	private ProgressBar pbLoading;
	public static ImageListViewAdapter imageListViewAdapter;
	private List<ImageContent> data;
	private String category = "all";
	private int page = 1;
	private View footerView = null;
	private final int STATE_FIRST_LOAD = 0;
	private final int STATE_LOAD_MORE = 1;
	private final int STATE_REFRESH = 2;
	private int loadState = STATE_FIRST_LOAD;

	@Override
	public SherlockFragmentActivity getSherlockActivity() {
		return super.getSherlockActivity();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Get the view from fragmenttab1.xml
		View view = inflater.inflate(R.layout.fragment_new_tab, container,
				false);
		lvNewFragment = (PullToRefreshListView) view
				.findViewById(R.id.lv_new_frament);
		pbLoading = (ProgressBar) view.findViewById(R.id.pb_Loading);

		firstLoad();

		lvNewFragment.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				refreshLoad();
			}
		});
		lvNewFragment.getRefreshableView().setOnScrollListener(
				new OnScrollListener() {

					@Override
					public void onScrollStateChanged(AbsListView view,
							int scrollState) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onScroll(AbsListView view,
							int firstVisibleItem, int visibleItemCount,
							int totalItemCount) {
						// TODO Auto-generated method stub
						if (view.getLastVisiblePosition() >= totalItemCount - 1) {
							if (data == null
									|| data.size() < (page * Common.Variable.DEFAULT_RECORDS)) {
								return;
							}
							loadMore();
						}
					}
				});
		return view;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
	}

	public void firstLoad() {
		page = 1;
		loadState = STATE_FIRST_LOAD;
		new LoadImageContentsFromServer().execute(getDataURL(page));
	}

	public void loadMore() {
		page++;
		loadState = STATE_LOAD_MORE;
		new LoadImageContentsFromServer().execute(getDataURL(page));
	}

	public void refreshLoad() {
		page = 1;
		loadState = STATE_REFRESH;
		new LoadImageContentsFromServer().execute(getDataURL(page));
	}

	public void showLoading() {
		pbLoading.setVisibility(View.VISIBLE);
		lvNewFragment.setVisibility(View.GONE);
		lvNewFragment.getRefreshableView().setVisibility(View.GONE);
	}

	public void hideLoading() {
		pbLoading.setVisibility(View.GONE);
		lvNewFragment.setVisibility(View.VISIBLE);
		lvNewFragment.getRefreshableView().setVisibility(View.VISIBLE);
	}

	public String getDataURL(int page) {
		// Page begin at 1 not at 0
		if (page == 0)
			page = 1;
		return String.format(Common.RequestURL.GET_IMAGE_CONTENTS, category,
				page);
	}

	public class LoadImageContentsFromServer extends
			AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			switch (loadState) {
			case STATE_FIRST_LOAD:
				showLoading();
				break;
			case STATE_LOAD_MORE:
				footerView = getActivity().getLayoutInflater().inflate(
						R.layout.lv_item_footer, null);
				lvNewFragment.getRefreshableView().addFooterView(footerView);
				break;
			case STATE_REFRESH:
				break;
			default:
				break;
			}
		}

		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(urls[0]);
			try {
				HttpResponse httpResponse = client.execute(httpGet);
				int status = httpResponse.getStatusLine().getStatusCode();
				if (status == HttpStatus.SC_OK) {
					HttpEntity getResponseEntity = httpResponse.getEntity();
					return EntityUtils.toString(getResponseEntity);
				}

			} catch (IOException e) {
				httpGet.abort();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (result != null) {
				switch (loadState) {
				case STATE_FIRST_LOAD:
					data = new ArrayList<ImageContent>();
					data.addAll(ImageContent
							.fromJsonArrayToImageContents(result));
					imageListViewAdapter = new ImageListViewAdapter(
							getActivity(), data);
					lvNewFragment.setAdapter(imageListViewAdapter);
					break;
				case STATE_LOAD_MORE:
					data.addAll(ImageContent
							.fromJsonArrayToImageContents(result));
					imageListViewAdapter.notifyDataSetChanged();
					break;
				case STATE_REFRESH:
					data.clear();
					data.addAll(ImageContent
							.fromJsonArrayToImageContents(result));
					imageListViewAdapter.notifyDataSetChanged();
					break;
				default:
					break;
				}
			} else {
				Log.d("kccc", "LoadImageContentsFromServer Fail");
			}
			switch (loadState) {
			case STATE_FIRST_LOAD:
				hideLoading();
				break;
			case STATE_LOAD_MORE:
				lvNewFragment.getRefreshableView().removeFooterView(footerView);
				break;
			case STATE_REFRESH:
				lvNewFragment.onRefreshComplete();
				break;
			default:
				break;
			}
		}
	}

}
